/**
 *  author :  tao.zhang
 *  create :  2013-4-12
 */
package edm.qunar.com;

import java.util.Queue;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.log4j.Logger;

/**
 * @author tao.zhang
 * 
 */
public class EmailWorker extends Thread {

	protected static final Logger logger = Logger.getLogger(EmailWorker.class
			.getName());

	private Queue<String> emailList;

	private EmailConfig cfg;

	public EmailWorker(Queue<String> emailList, final EmailConfig cfg,
			final int id) {
		super("Worker" + id);
		this.emailList = emailList;
		this.cfg = cfg;

	}

	@Override
	public void run() {

		while (true) {
			Object o = emailList.poll();
			String email;
			if (null == o) {
				logger.info("邮件队列已经为空，工作线程" + getName() + "退出。");
				return;
			} else {
				email = o.toString();
			}

			HtmlEmail hm = new HtmlEmail();
			try {
				hm.addTo(email);
				hm.setHostName(cfg.getSmtp());
				hm.setFrom(cfg.getFrom());
				hm.setCharset(cfg.getCharset());
				hm.setSubject(cfg.getSubject());
				hm.setHtmlMsg(cfg.getHtmlMsg());
				// hm.setTextMsg("Your hm client does not support HTML messages");
				hm.send();
				logger.info("线程" + getName() + "发送成功："
						+ hm.getToAddresses().toString());
			} catch (EmailException e) {
				logger.error("线程" + getName() + "发送失败："
						+ hm.getToAddresses().toString());
				logger.error(e.getMessage());
			}
		}
	}

	public Queue<String> getEmailList() {
		return emailList;
	}

	public void setEmailList(Queue<String> emailList) {
		this.emailList = emailList;
	}

	public EmailConfig getCfg() {
		return cfg;
	}

	public void setCfg(EmailConfig cfg) {
		this.cfg = cfg;
	}

}
